<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择门店">
          <el-option
            v-for="item in slectDeptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班次" prop="classes">
        <el-select v-model="queryParams.classes" placeholder="请选择班次" clearable>
          <el-option
            v-for="dict in dict.type.class"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售员">
        <el-select v-model="queryParams.userId" placeholder="请选择销售员">
            <el-option
              v-for="item in slectUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="inventoryId">
        <el-input
          v-model="queryParams.inventoryId"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="盘点日期" prop="checkTime">
        <el-date-picker clearable
          v-model="queryParams.checkTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择盘点日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:checkGgl:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:checkGgl:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:checkGgl:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:checkGgl:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkGglList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="门店" align="center" prop="deptName" />
      <!-- <el-table-column label="产品名称" align="center" prop="inventoryName" /> -->
      <el-table-column label="班次" align="center" prop="classes">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.classes == 'Morning'" type="success">
            <dict-tag :options="dict.type.class" :value="scope.row.classes"/>
          </el-tag>
          <el-tag v-if="scope.row.classes == 'Late'" type="danger">
            <dict-tag :options="dict.type.class" :value="scope.row.classes"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销售员" align="center" prop="checkUserName" />
      <!-- <el-table-column label="盘点数量" align="center" prop="num" />
      <el-table-column label="盘点数量" align="center" prop="packageNum" /> -->
      <el-table-column label="盘点日期" align="center" prop="checkTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:checkGgl:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:checkGgl:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改盘点--刮刮乐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-card class="box-card"> -->
          <div slot="header" class="clearfix">
            <span v-if="form.classes ==='Morning'">早盘点</span>
            <span v-if="form.classes ==='Late'">晚盘点</span>
            <span v-if="form.classes ==='All'">全天班盘点</span>
          </div>
          <div>

            <div v-if="form.classes ==='Morning'">
              <el-row>
                <el-col :span="24">

                  <div>
                    <el-row>
                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            早即开票库存盘点情况
                            <font style="color: red;"><b> {{ invCount }}</b></font>
                          </font>
                        </el-tag>
                      </el-col>
                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            早盘点库存昨日差额
                            <font style="color: red;"><b> {{ invYesterdayDiff }}</b></font>
                          </font>
                        </el-tag>
                      </el-col>
                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            早盘点现金昨日差额
                            <font style="color: red;"><b> {{ invCashDiff }}</b></font>
                          </font>
                        </el-tag>
                      </el-col>
                    </el-row>
                    <br/>
                    </div>
                </el-col>
              </el-row>

              <el-form-item label-width="180px" label="早现金盘点情况" prop="morningCashDesc">
                <el-input type="number"   v-model="form.morningCashDesc" placeholder="请输入内容" @blur="morningCashDescInput"></el-input>
              </el-form-item>
              <el-form-item label-width="180px" label="微信余额盘点情况" prop="morningCashDesc">
                <el-input type="number"   v-model="form.wxBalance" placeholder="请输入内容"></el-input>
              </el-form-item>
              <div>
                <!-- <span>上一天对盘点特殊情况的备注</span>
                <br/> -->
                <el-form-item label-width="180px" label="" prop="morningCashDesc">
                  <el-input
                    type="textarea"
                    placeholder="填写备注信息"
                    v-model="form.remark"
                    maxlength="30"
                    show-word-limit
                  />
                </el-form-item>
              </div>
              <el-form-item label="核对人员" prop="checkUserId">
                <el-select v-model="form.checkUserId" placeholder="请选择核对人员">
                  <el-option
                    v-for="item in slectUserOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

            </div>
            <div v-if="form.classes ==='Late'">
              <el-row>
                <el-col :span="24">

                  <div>
                    <el-row>
                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            晚即开票库存盘点情况
                            <font style="color: red;"><b> {{ wbInvMoney }}</b></font>
                          </font>
                        </el-tag>

                      </el-col>
                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            剩余包数
                            <font style="color: red;"><b> {{ wrap }}</b></font>
                          </font>
                        </el-tag>

                      </el-col>

                      <el-col :span="8">
                        <el-tag effect="plain" size="medium">
                          <font style="font-size: 20px;">
                            剩余张数
                            <font style="color: red;"><b> {{ zhang }}</b></font>
                          </font>
                        </el-tag>

                      </el-col>
                    </el-row>
                    <br/>

                    </div>

                </el-col>
              </el-row>
            </div>

            <div v-if="form.classes ==='Late'"></div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="门店" prop="deptId">
                  <el-select v-model="form.deptId" placeholder="请选择门店" @change="slectDeptEevent">
                    <el-option
                      v-for="item in slectDeptOptions"
                      :key="item.deptId"
                      :label="item.deptName"
                      :value="item.deptId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

            <!--  <el-col :span="12">
                <el-form-item label="销售员" prop="userId">
                  <el-select v-model="form.userId" placeholder="请选择销售员">
                    <el-option
                      v-for="item in slectUserOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>-->

            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="班次" prop="classes">
                  <el-radio-group v-model="form.classes" @change="classesRadio" :disabled="classesRadioFlge">
                    <el-radio
                      v-for="dict in dict.type.class"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="盘点日期" prop="checkTime">
                  <el-date-picker clearable
                    v-model="form.checkTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择盘点日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="核对人员" prop="checkUserId">
                  <el-select v-model="form.checkUserId" placeholder="请选择核对人员">
                    <el-option
                      v-for="item in slectUserOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
      </el-form>
      <el-divider content-position="left">即开票</el-divider>
      <vxe-table
          border
          show-overflow
          keep-source
          ref="xTable"
          max-height="400"
          :data="invData"
          :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true}"
          highlight-current-row
          >
          <vxe-table-column type="checkbox" width="60"></vxe-table-column>
          <vxe-table-column field="materialName" title="产品名称" sortable ></vxe-table-column>
          <vxe-table-column field="money" title="面值" ></vxe-table-column>
          <vxe-table-column field="price" title="单包价格"></vxe-table-column>
          <!-- <vxe-table-column field="inpackageNum" title="单包片数" ></vxe-table-column> -->
           <!--<vxe-table-column field="sheetNum" title="库存剩余张数"></vxe-table-column> -->
          <vxe-table-column field="outPackageNum" title="库存（包）" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template v-slot:edit="{ row }">
              <vxe-input type="number" :min="0" v-model="row.outPackageNum" @blur="editOutNum(row)"></vxe-input>
              <!-- <vxe-input type="number" :min="0" v-model="row.invPackageNum"></vxe-input> -->
            </template>
          </vxe-table-column>
          <vxe-table-column field="outNum" title="库存（张）" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template v-slot:edit="{ row }">
              <vxe-input type="number" :min="0" v-model="row.outNum" @blur="editOutNum(row)"></vxe-input>
            </template>
          </vxe-table-column>
          <!-- <vxe-column title="总价">
            <template #default="{ row }">
              <span>{{ countAmount(row) }} 元</span>
            </template>
          </vxe-column> -->
        </vxe-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCheckGgl, getCheckGgl, delCheckGgl, addCheckGgl, updateCheckGgl,wSave ,getLastEvenReport,zSave,getInvList} from "@/api/system/checkGgl";
import { listDept } from "@/api/system/dept";
import { getSalesUserByUserName } from "@/api/system/user";
import { getInvByDeptIdAndSalesIdAndClassCode } from "@/api/system/inventoryGgl";
export default {
  name: "CheckGgl",
  dicts: ['class'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      classesRadioFlge: false,
      // 总条数
      total: 0,
      // 盘点--刮刮乐表格数据
      checkGglList: [],
      invData:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        inventoryId: null,
        type: null,
        num: null,
        packageNum: null,
        checkTime: null,
      },
      //早即开票库存盘点情况
      invCount: 0,
      //早盘点库存昨日差额
      invYesterdayDiff: 0,
      //早盘点现金昨日差额
      invCashDiff: 0,
      morningCashDesc: 0,
      wbInvMoney: 0,
      wrap: 0,
      zhang: 0,
      // 表单参数
      form: {
        invCount: 0,
        classes: 'Morning',
        morningCashDesc: 0,
        //表头 早盘点库存昨日差额
        invYesterdayDiff: 0,
        // 表单早盘点现金昨日差额
        invCashDiff:0,
        checkGglLine: [],
        checkTime: null
      },
      // 表单校验
      rules: {
      },
      slectDeptOptions:[],
      slectUserOptions: []

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询盘点--刮刮乐列表 */
    getList() {
      this.loading = true;
      listCheckGgl(this.queryParams).then(response => {
        this.checkGglList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listDept({"parentId":100}).then(response => {
        this.slectDeptOptions = response.data;
      });
      getSalesUserByUserName({"userName":""}).then(response => {
        this.slectUserOptions = response.data;
      });
    },
    morningCashDescInput(){
      getInvList({deptId: this.form.deptId}).then(response => {
          this.form.invCashDiff  =(response.data.invFund - this.form.morningCashDesc);
          this.invCashDiff = this.form.invCashDiff;
       });
    },
    slectDeptEevent(data){
      getInvByDeptIdAndSalesIdAndClassCode({deptId:data}).then(response => {
          this.invData = response.data;
      });
    },
    //切换班次事件
    classesRadio(){
      if(this.form.classes == 'Morning'){
            //早班填报数据
            //1.先早即开票库存情况
            const data = this.$refs.xTable.data;

            //1.先计算现金差额 this.form.deptId,this.form.classes,this.checkTime
            getInvList({deptId: this.form.deptId}).then(response => {
              this.calcMorningForm(data,response.data.invAmount);
            });

      }else if(this.form.classes == 'Late'){
        const data = this.$refs.xTable.data;
          if(data) {
            const lateForm = this.calcLateForm(data);
            this.wbInvMoney = lateForm.wbInvMoney;
            this.wrap = lateForm.wrap;
            this.zhang = lateForm.zhang;
          }
      }
    },
    //计算行总价格
    countAmount(row){
        //单价包
        const price = row.price;
          //面值金额
            const money = row.money;
          // 单包张数
          const packageNum = row.packageNum;
          //剩余库存
          const invPackageNum= row.invPackageNum;

          //剩余张数
          const invNum= row.invNum;
          if(this.invPackageNum === ""){
            this.invPackageNum = "0";
          }
          if(this.invNum === ""){
            this.invNum = "0";
          }
          var sum = 0;
          if(invPackageNum){
            sum = (Number(invPackageNum) * price);
          }
          if(invNum){
            sum += invNum * money
          }
          return sum;
    },
    editOutNum(row){
        if(this.form.classes == 'Morning'){
            //早班填报数据
            //1.先早即开票库存情况
            const data = this.$refs.xTable.data;

            //1.先计算现金差额 this.form.deptId,this.form.classes,this.checkTime
            getInvList({deptId: this.form.deptId}).then(response => {
                  //计算表头
                  this.calcMorningForm(data,response.data);
                   //3.早盘点现金昨日差额
                  //  const zchCheckFundEntiy = response.data.zchCheckFundEntiy;
                  //  if(zchCheckFundEntiy){
                  //     this.invCashDiff =this.form.morningCashDesc - (zchCheckFundEntiy.xj + zchCheckFundEntiy.hsk + zchCheckFundEntiy.zfb + zchCheckFundEntiy.szRmb)
                  //   }
            });
        }

        //晚班
        if(this.form.classes == 'Late'){
          const data = this.$refs.xTable.data;
          if(data) {
            const lateForm = this.calcLateForm(data);
            this.wbInvMoney = lateForm.wbInvMoney;
            this.wrap = lateForm.wrap;
            this.zhang = lateForm.zhang;
          }
        }
    },
    //早班表头计算
    calcMorningForm(data,invData){
        //早即开票库存盘点情况
        this.invCount =data.reduce((entity,obj) => {
          //单价包
          const price = obj.price;
          //面值金额
          const money = obj.money;
          // 单包张数
          const packageNum = obj.inpackageNum;
          //剩余库存
          const invPackageNum= obj.outPackageNum;
          //剩余张数
          const invNum= obj.outNum;
            if(this.invPackageNum === ""){
              this.invPackageNum = "0";
            }
            if(this.invNum === ""){
              this.invNum = "0";
            }

            if(invPackageNum){
              entity += (Number(invPackageNum) * price);
            }

            if(invNum){
              entity += invNum * money
            }
            return entity;
        },0);
        //
        this.invYesterdayDiff = (invData.invAmount - this.invCount);
        this.form.invYesterdayDiff = this.invYesterdayDiff;
        if(invData.invFund){
          this.invCashDiff = (invData.invFund - this.invCashDiff);
        }
    },
    //晚班表头计算
   calcLateForm(data){
          const wbInvMoney =data.reduce((entity,obj) => {
            //单价包
            const price = obj.price;
            //面值金额
              const money = obj.money;
            // 单包张数
            const packageNum = obj.inpackageNum;

            //剩余库存
            const invPackageNum= obj.outPackageNum;

            //剩余张数
            const invNum= obj.outNum;
            if(this.invPackageNum === ""){
              this.invPackageNum = "0";
            }
            if(this.invNum === ""){
              this.invNum = "0";
            }

            if(invPackageNum){
              entity += (Number(invPackageNum) * price);
            }

            if(invNum){
              entity += invNum * money
            }
            return entity;
         },0);
          //计算剩余包数
          const wrap = data.reduce((sum,entity) => {
            if(!entity.outPackageNum) {
              sum += 0;
            }
            sum += Number(entity.outPackageNum)
            return sum;
          },0);

          //计算剩余张数
          const zhang = data.reduce((sum,entity) => {
            if(!entity.outNum) {
              sum += 0;
            }
            sum+= Number(entity.outNum)
            return sum;
          },0);

          return { "wbInvMoney": wbInvMoney ,"wrap": wrap,"zhang": zhang}
   },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        inventoryId: null,
        type: null,
        num: null,
        packageNum: null,
        classes: 'Morning',
        morningCashDesc:0,
        checkTime: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,

      };
      this.invData =[];
      this.wbInvMoney= 0;
      this.wrap =0;
      this.zhang =0;
      this.invCount=0;
      this.invYesterdayDiff= 0;
      this.invCashDiff= 0;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.classesRadioFlge =false;
      this.open = true;
      this.title = "添加即开票盘点 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.classesRadioFlge =true;
      const id = row.id || this.ids
      getCheckGgl(id).then(response => {
        this.form = response.data;
        this.invData = response.data.checkGglLineList;
        this.open = true;
        if(response.data.classes =='Late'){
          this.calcLateForm(response.data.checkGglLineList);
        }else if(response.data.classes =='Morning'){
          this.invCount = response.data.invCount;
          this.invYesterdayDiff = response.data.invYesterdayDiff;
          this.invCashDiff = response.data.invCashDiff;
          this.invData = response.data.checkGglLineList;
        }
        this.title = "修改即开票盘点 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //早班提交
          if(this.form.classes ==='Morning'){
              this.form.checkGglLine =  this.$refs.xTable.data;
              this.form.invCount =this.invCount;
              this.form.invYesterdayDiff =this.invYesterdayDiff;
              this.form.invCashDiff =this.invCashDiff;
            if (this.form.id != null) {
              updateCheckGgl(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }else {
              //保存
              zSave(this.form).then(response => {
                this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.getList();
              });
            }
          }else
          //晚班提交
          if(this.form.classes ==='Late'){
            this.form.checkGglLine =  this.$refs.xTable.data;
            console.log(this.form);
            if (this.form.id != null) {
            updateCheckGgl(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }else {
            wSave(this.form).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.getList();
            });
          }
        }

          // if (this.form.id != null) {
          //   updateCheckGgl(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addCheckGgl(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除即开票盘点编号为"' + ids + '"的数据项？').then(function() {
        return delCheckGgl(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/checkGgl/export', {
        ...this.queryParams
      }, `checkGgl_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
